<template>
  <div class="content-center-wrap">
    <Card :bordered="false">
      <div slot="title" class="clearfix">
        <span class="fl card-tit">气量热力图</span>
        <div class="fr">
          <DatePicker
            type="date"
            size="small"
            placement="bottom-end"
            @on-change="handleChangeHeatmapBmapDate"
            placeholder="选择日期"
            v-model="selectedDate"
            style="width:130px"
          ></DatePicker>
        </div>
        <div class="tc">
          <Button type="info" size="small" @click="refreshPage"> <Icon type="md-refresh" />刷新</Button>
        </div>
      </div>
      <div class="chart-box" @mouseenter.stop="heatmapMouseenterHandle" @mouseleave="heatmapMouseleaveHandle">
        <e-heatmap
          id="map"
          :chartData="heatmapBmapData"
          :markPoints="minimapCenter"
          @q-finished="heatmapBmapFinished"
        />
        <div class="minimap-box">
          <e-heatmap
            id="minimap"
            :chartData="miniMapData"
            @q-click="handleMiniMapClick"
            @q-dblClick="handleMiniMapDblclick"
          />
        </div>
        <div class="play-wrap" v-show="showPlayWrap">
          <div class="play-box">
            <div class="play-btn" @click="handlePlayClick" v-show="showPlayBtn" title="播放">
              <Icon type="ios-play" />
            </div>
            <div class="play-btn" @click="handleStopClick" v-show="!showPlayBtn" title="暂停">
              <Icon type="md-pause" />
            </div>
            <div class="process-box" v-show="showProgress">
              <Tooltip always :content="showOnceMonthDate" style="width:100%">
                <Progress :percent="heatmapProcessPercent" :stroke-width="10" text-inside />
              </Tooltip>
            </div>
          </div>
        </div>
        <Spin fix size="large" v-if="heatMapLoading">
          <Icon type="ios-loading" size="20" class="demo-spin-icon-load"></Icon>
          <div>图表生成中...</div>
        </Spin>
      </div>
    </Card>
    <!-- 树形关系图 -->
    <Modal
      v-model="showTreeFlag"
      key="dailyviewMeterDetailModal"
      class="tree-modal"
      :title="'表具ID: ' + currentSelectedMeterId"
      @on-cancel="onTreeCancel"
      width="96%"
      :styles="{ top: '30px', height: '85%' }"
    >
      <div
        id="dailyviewMeterDetail"
        :is="userAndMeterInfoTpl"
        :content="meterDetailData"
        :currentMeterId="currentSelectedMeterId"
      ></div>
      <div slot="footer">
        <Button @click="onTreeCancel" ghost>关闭</Button>
      </div>
    </Modal>
    <!-- K线图 -->
    <Modal
      v-model="showKxianFlag"
      class="kxian-modal modal"
      :title="currentModalMonth"
      @on-cancel="onKxianCancel"
      width="96%"
      :styles="{ top: '30px', height: '85%' }"
    >
      <div class="chart-box">
        <div :is="detailComponent" :options="gasUseDetailOptions" :currentMeterId="currentSelectedMeterId"></div>
      </div>
      <div slot="footer">
        <Button @click="onKxianCancel" ghost>关闭</Button>
      </div>
    </Modal>
  </div>
</template>
<script>
import { merge, each } from 'lodash'
import { createNamespacedHelpers } from 'vuex'
import { eHeatmapOptions, minimapOptions } from './chartOptions'
import dayjs from 'dayjs'
const { mapState, mapActions } = createNamespacedHelpers('dailyview')

export default {
  name: 'dailyview-content-center',
  components: {
    EHeatmap: () => import('@/commons/charts/EHeatmap'),
    GasConsumptionDetail: () => import('@/commons/GasConsumptionDetail'),
    UserAndMeterDetailETree: () => import('@/commons/UserAndMeterDetailETree')
  },
  data() {
    return {
      mapDefaultCenter: null,
      showPlayBtn: true,
      showPlayWrap: false,
      showProgress: false,
      showOnceMonthDate: undefined,
      showOnceMonthEndDate: undefined,
      heatmapProcessPercent: 0,
      showTreeFlag: false,
      userAndMeterInfoTpl: null,
      meterDetailData: null,
      showKxianFlag: false,
      detailComponent: null,
      gasUseDetailOptions: {
        meterId: null,
        month: null
      },
      heatmapSwiperFinished: true,
      heatmapSwiperFetchTimer: null,
      heatmapSwiperStopFlag: false
    }
  },
  beforeDestroy() {
    if (this.heatmapSwiperFetchTimer) {
      clearTimeout(this.heatmapSwiperFetchTimer)
    }
  },
  computed: {
    ...mapState([
      'currentSelectedMeterId',
      'heatMapLoading',
      'heatMapList',
      'minimapCenter',
      'defaultPointRadius',
      'currentSelectedMapDate',
      'defaultDate',
      'meterTreeDetail',
      'heatMapSwiperState'
    ]),
    heatmapBmapData() {
      const _serList = []
      each(this.heatMapList, item => {
        const { count, latitude, longitude } = item
        _serList.push([longitude, latitude, count])
      })

      return merge({}, eHeatmapOptions, {
        bmap: {
          center: this.mapDefaultCenter
        },
        series: [
          {
            data: _serList
          }
        ]
      })
    },
    miniMapData() {
      return merge({}, minimapOptions, {
        bmap: {
          center: this.minimapCenter || this.mapDefaultCenter
        },
        series: [
          {
            data: [
              {
                name: this.currentSelectedMeterId,
                value: [...this.minimapCenter, this.defaultPointRadius]
              }
            ]
          }
        ]
      })
    },
    selectedDate: {
      get() {
        return this.currentSelectedMapDate || this.defaultDate
      },
      set(val) {
        // do nothing
      }
    },
    currentModalMonth() {
      return this.selectedDate ? `当前时间: ${dayjs(this.selectedDate).format('YYYY-MM')}` : '详情'
    }
  },
  mounted() {
    this.mapDefaultCenter = this.$store.getters.mapCenter
    this.loadHeatMapData()
  },
  methods: {
    ...mapActions([
      'changeCurrentSelecteMapDate',
      'loadHeatMapData',
      'loadHeatMapData',
      'loadMeterTreeDetail',
      'refresh',
      'changeHeatMapSwiperState',
      'loadTableData'
    ]),
    handleChangeHeatmapBmapDate(date) {
      this.changeHeatMapSwiperState(true)
      this.changeCurrentSelecteMapDate(date)
      this.loadHeatMapData()
      this.loadTableData()
    },
    refreshPage() {
      this.refresh()
    },
    heatmapMouseenterHandle() {
      if (this.heatmapSwiperFinished) {
        this.showPlayWrap = true
      }
    },
    heatmapMouseleaveHandle() {
      if (this.heatmapSwiperFinished) {
        this.clearHeatMapSwiperData()
      }
    },
    handleMiniMapClick(params) {
      this.changeHeatMapSwiperState(true)
      const { name } = params
      this.gasUseDetailOptions = {
        ...this.gasUseDetailOptions,
        meterId: name,
        month: this.currentSelectedMapDate
          ? dayjs(this.currentSelectedMapDate).format('YYYY-MM')
          : this.defaultDate && dayjs(this.defaultDate).format('YYYY-MM')
      }

      this.showKxianFlag = true
      this.$nextTick(() => {
        this.detailComponent = 'GasConsumptionDetail'
      })
    },
    async handleMiniMapDblclick(params) {
      this.changeHeatMapSwiperState(true)
      const { name } = params
      const { code, date } = await this.loadMeterTreeDetail(name)
      if (code === 200) {
        this.$Loading.finish()
        this.meterDetailData = date
        this.showTreeFlag = true
        this.$nextTick(() => {
          this.userAndMeterInfoTpl = 'UserAndMeterDetailETree'
        })
      }
    },
    handlePlayClick() {
      this.changeHeatMapSwiperState(false)
      const cDate = this.showOnceMonthDate || this.selectedDate
      this.heatmapSwiperStopFlag = false
      this.heatmapSwiperFinished = false
      this.showPlayBtn = false
      this.showProgress = true
      if (!this.showOnceMonthEndDate) {
        // 往前一个月
        const endDate = dayjs(cDate).subtract(30, 'day')
        this.showOnceMonthEndDate = endDate.format('YYYY-MM-DD')
      }
      this.showHeatmapByDateFetch(cDate)
    },
    handleStopClick() {
      this.heatmapSwiperStopFlag = true
      this.showPlayBtn = true
    },
    onTreeCancel() {
      this.showTreeFlag = false
      this.userAndMeterInfoTpl = null
      this.meterDetailData = null
    },
    onKxianCancel() {
      this.showKxianFlag = false
      this.detailComponent = null
      this.treemapTableTemplate = null
    },
    clearHeatMapSwiperData() {
      if (this.heatmapSwiperFetchTimer) {
        clearTimeout(this.heatmapSwiperFetchTimer)
      }
      this.heatmapSwiperFinished = true
      this.showPlayBtn = true
      this.showPlayWrap = false
      this.showProgress = false
      this.showOnceMonthDate = undefined
      this.showOnceMonthEndDate = undefined
      this.heatmapProcessPercent = 0
    },
    heatmapBmapFinished() {
      if (this.heatmapSwiperFetchTimer) {
        clearTimeout(this.heatmapSwiperFetchTimer)
      }
      if (this.heatMapSwiperState) {
        this.clearHeatMapSwiperData()
      } else {
        this.heatmapSwiperFetchTimer = setTimeout(() => {
          this.showHeatmapByDateFetch(this.showOnceMonthDate)
        }, 600)
      }
    },
    showHeatmapByDateFetch(date) {
      if (this.heatmapSwiperStopFlag) {
        clearTimeout(this.heatmapSwiperFetchTimer)
        return
      }
      const currentDate = dayjs(date)
        .subtract(1, 'day')
        .format('YYYY-MM-DD')
      const _spaceNum = dayjs(currentDate).diff(dayjs(this.showOnceMonthEndDate), 'day')
      if (_spaceNum >= 0) {
        this.showOnceMonthDate = currentDate
        const _pro = parseInt(((30 - _spaceNum) / 30) * 100)
        this.heatmapProcessPercent = _pro
        this.loadHeatMapData({
          tId: currentDate
        })
      } else {
        clearTimeout(this.heatmapSwiperFetchTimer)
        this.heatmapSwiperFinished = true
        this.showPlayBtn = true
        this.showOnceMonthEndDate = undefined
      }
    }
  }
}
</script>
<style lang="less" scoped>
@deep: ~'>>>';

.content-center-wrap {
  width: 100%;
  height: 100%;

  .minimap-box {
    position: absolute;
    top: 0;
    right: 0;
    width: 20%;
    height: 20%;
  }
  .chart-box {
    position: relative;
    width: 100%;
    height: 100%;

    &:hover {
      .play-wrap {
        display: block;
      }
    }
  }
}
.play-wrap {
  position: absolute;
  left: 0;
  bottom: 0;
  right: 0;
  padding: 20px 40px;
  z-index: 99;
}

.play-box {
  position: relative;
  padding-left: 40px;
  height: 28px;

  .play-btn {
    position: absolute;
    left: 0;
    width: 28px;
    height: 28px;
    text-align: center;
    cursor: pointer;

    .ivu-icon {
      font-size: 22px;
      margin-top: 3px;
    }
  }
  .process-box {
    @{deep} .ivu-progress-inner-text {
      margin-top: -7px;
    }
  }
}
.modal {
  .chart-box {
    width: 100%;
    height: 100%;
  }
}
</style>
